package com.xlh.codeserver.component;

import java.net.URI;
import java.util.Arrays;
import java.util.stream.Collectors;

import com.xlh.codeserver.dao.ContainerDao;
import com.xlh.codeserver.entity.Container;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * codeserver 重写url
 */
@Component
@Slf4j
public class RewriteUrlFilter implements GlobalFilter, Ordered {

    @Autowired
    private ContainerDao containerDao;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        URI uri = exchange.getRequest().getURI();
        String uriQuery = uri.getQuery();
        String path = uri.getPath();
        String[] split = path.split("/");
        Container container = this.containerDao.selectByBaseUrl(split[2]);
        // 获取2 后面的字符串
        String after =  Arrays.stream(split).skip(3).collect(Collectors.joining("/"));
        try {
            if(uriQuery == null){
                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, new URI(uri.getScheme()+"://" +container.getAddr()+"/"+after ));
            }else{
                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, new URI(uri.getScheme()+"://" +container.getAddr()+"/"+after +"?" + uriQuery));
            }
        } catch (Exception var8) {
           log.error("异常打印：", var8);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2147483646;
    }

}